package logic

import (
	"cloud-disk/core/define"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileListLogic {
	return &UserFileListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileListLogic) UserFileList(req *types.UserFileListRequest, UserIdentity string) (resp *types.UserFileListResponse, err error) {
	userFile := make([]*types.UserFile, 0)
	resp = new(types.UserFileListResponse)
	pageSize := req.Size
	if pageSize == 0 {
		pageSize = define.PageSize
	}
	page := req.Page
	if page == 0 {
		page = 1
	}
	//偏移量用来计算取第几页数据
	offSet := (page - 1) * pageSize
	var count int64
	rows, err := l.svcCtx.DbConn.Table("user_repository").
		Select("user_repository.id,user_repository.name,user_repository.identity,user_repository.repository_identity,user_repository.ext,"+
			"repository_pool.path,repository_pool.size").
		Joins("left join repository_pool on user_repository.repository_identity=repository_pool.identity").
		Where("user_identity=? AND parent_id=? AND user_repository.deleted_at IS NULL", UserIdentity, req.Id).
		Limit(int(pageSize)).
		Offset(int(offSet)).
		Scan(&userFile).Rows()
	for rows.Next() {
		count++
	}
	if err != nil {
		return
	}
	resp.List = userFile
	resp.Count = count
	return
}
